
package com.pekall.music.util;

import java.util.ArrayList;
import java.util.List;

import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.provider.MediaStore;

import com.pekall.music.model.Music;

public class MusicOperate {

    String[] mCursorCols = new String[] {
            "audio._id AS _id", MediaStore.Audio.Media.ARTIST, MediaStore.Audio.Media.ALBUM,
            MediaStore.Audio.Media.TITLE, MediaStore.Audio.Media.DATA,
            MediaStore.Audio.Media.MIME_TYPE, MediaStore.Audio.Media.ALBUM_ID,
            MediaStore.Audio.Media.ARTIST_ID, MediaStore.Audio.Media.DURATION
    };

    Uri MUSIC_URL = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;

    /**
     * 获取所有歌曲数据,未排序
     * 
     * @param context
     * @return
     */
    public List<Music> getAllMusic(Context context) {

        List<Music> mListMusic = new ArrayList<Music>();
        // Cursor cursor = context.getContentResolver().query(
        // MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
        // new String[] {
        // MediaStore.Audio.Media.TITLE, MediaStore.Audio.Media.DURATION,
        // MediaStore.Audio.Media.ARTIST, MediaStore.Audio.Media._ID,
        // MediaStore.Audio.Media.DISPLAY_NAME
        // }, null, null, null);
        Cursor cursor = context.getContentResolver().query(MUSIC_URL, mCursorCols,
                "duration > 100000", null, null);

        cursor.moveToFirst();
        for (int i = 0; i < cursor.getCount(); i++) {
            mListMusic.add(cursorToMusic(cursor));
            cursor.moveToNext();
        }

        return mListMusic;
    }

    /**
     * cursor转化为music
     * 
     * @param cursor
     * @return
     */
    public Music cursorToMusic(Cursor cursor) {
        Music music = new Music();

        music.id = cursor.getInt(0);
        music.artist = cursor.getString(1);
        music.album = cursor.getString(2);
        music.title = cursor.getString(3);
        music.path = cursor.getString(4);
        music.mimeType = cursor.getString(5);
        music.albumId = cursor.getInt(6);
        music.artistId = cursor.getInt(7);
        music.duration = toTime(cursor.getInt(8));

        if (cursor.getString(1).equals("<unknown>"))
            music.artist = "未知";
        return music;
    }

    /**
     * 播放秒数转化为时分
     * 
     * @param time
     * @return
     */
    public String toTime(int time) {
        time /= 1000;
        int minute = time / 60;
        int second = time % 60;
        minute %= 60;
        return String.format("%02d:%02d", minute, second);
    }

}
